package edu.iyte.ceng431.hw2.pos.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

import edu.iyte.ceng431.hw2.pos.db.Insert;
import edu.iyte.ceng431.hw2.pos.db.Search;
import edu.iyte.ceng431.hw2.pos.model.Register;
import edu.iyte.ceng431.hw2.pos.model.Return;
import edu.iyte.ceng431.hw2.pos.model.Sale;
import edu.iyte.ceng431.hw2.pos.model.SaleLineItem;
import edu.iyte.ceng431.hw2.pos.view.MainFrame;
import edu.iyte.ceng431.hw2.pos.view.SaleListModel;

public class ReturnController {
	private MainFrame mainView;
	private Sale currentSale;
	private Return newReturn;

	public ReturnController(MainFrame mainView) {
		super();
		this.mainView = mainView;
		this.mainView.addGetSaleItemsListener(new GetSaleItemsListener());
		this.mainView.addReturnListener(new ReturnListener());
	}

	class GetSaleItemsListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			try {
				currentSale = Search.getSale(Integer.parseInt(mainView
						.getSaleIdTextField().getText()));
				mainView.getReturnSaleItemList().setModel(
						new SaleListModel(currentSale.getSaleLineItems()));
			} catch (NumberFormatException nfex) {
				JOptionPane.showMessageDialog(mainView, "Invalid Sale ID.",
						"Error", JOptionPane.ERROR_MESSAGE);
			} catch (NullPointerException nfex)
			{
				JOptionPane.showMessageDialog(mainView, "Invalid Sale ID.",
						"Error", JOptionPane.ERROR_MESSAGE);
			}
		}

	}

	class ReturnListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			double temp=0;
			try {

				int quantity = Integer.parseInt(mainView.getReturnQuantityTextField()
						.getText());
				SaleLineItem saleLineItem = (SaleLineItem) mainView
						.getReturnSaleItemList().getSelectedValue();
				if (quantity <= 0 || quantity > saleLineItem.getQuantity()
						|| saleLineItem == null)
					throw new NumberFormatException();
				newReturn = new Return(quantity, saleLineItem);
				Insert.insertReturn(newReturn);
				double returnedMoney = quantity * saleLineItem.getUnitPrice();
				JOptionPane.showMessageDialog(null,
						"Item successfully returned!\nReturned money : "
								+ returnedMoney);
				mainView.getMainTabbedPane().setSelectedIndex(0);
				Register reg = mainView.getReg();
				temp = reg.getBalance();
				reg.setBalance(temp - returnedMoney);
				mainView.getBalanceTextField().setText(String.valueOf(reg.getBalance()));

			} catch (NumberFormatException nfex) {
				JOptionPane.showMessageDialog(mainView,
						"Invalid quantity or Sale Item is Not Selected.",
						"Error", JOptionPane.ERROR_MESSAGE);
			}
		}

	}

}
